package com.xplay.xpocker.meta.room;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.xplay.xpocker.meta.rule.MetaRoomRule;
import com.xplay.xpocker.meta.user.MetaUserChannel;
import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;

/**
 * 顶层房间信息
 * <p>
 * T  自定义房间内容
 * <p>
 * R  房间规则
 * <p>
 * U  自定义房间玩家信息
 *
 *
 * 创建房间使用的 顶层类   但是通常情况下有一些 自定义的信息
 * 所以在使用子类的时候 如果需要将父类转换成 子类 这里使用了 jackson 序列化  getRoomInfo 返回子类
 *
 * @author wanjie
 * @date 2021/3/28 16:21
 */
@Data
public class MetaRoomEntity<T extends MetaRoomEntity, R extends MetaRoomRule, U extends MetaUserChannel> implements Serializable {

    private static final long serialVersionUID = -4828545085253095799L;
    /**
     * 玩家座位信息
     */

    protected HashMap<String, U> allUserInfo;
    protected String roomType;
    protected String roomRule;
    // 房间编号
    protected String code;
    // 数据库 房间  序列ID
    protected Integer dbSequence;
    // 数据库 当前局 的 序列ID
    protected Integer currentGameSequence;

    public R getRoomRule(Class<R> clazz) {
        if (null == this.roomRule || this.roomRule.equals("")) {
            return null;
        }
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            return objectMapper.readValue(this.roomRule, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public T getRoomInfo(Class<T> clazz) {
        try {
            String result = new ObjectMapper().writeValueAsString(this);
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            return objectMapper.readValue(result, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void removeUser(String userId) {
        if (this.getAllUserInfo() != null) {
            allUserInfo.remove(userId);
        }

    }

}
